package com.seckillpro.seckill_pro.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seckillpro.seckill_pro.exception.GlobalException;
import com.seckillpro.seckill_pro.mapper.TUserMapper;
import com.seckillpro.seckill_pro.pojo.TUser;
import com.seckillpro.seckill_pro.service.ITUserService;
import com.seckillpro.seckill_pro.utils.CookieUtil;
import com.seckillpro.seckill_pro.utils.MD5Util;
import com.seckillpro.seckill_pro.utils.UUIDUtil;
import com.seckillpro.seckill_pro.utils.ValidatorUtil;
import com.seckillpro.seckill_pro.vo.LoginVo;
import com.seckillpro.seckill_pro.vo.RegisterVo;
import com.seckillpro.seckill_pro.vo.RespBean;
import com.seckillpro.seckill_pro.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyx
 * @since 2021-03-03
 */
@Slf4j
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {


    private static final String salt = "1a2b3c4d";
    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param loginVo
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        log.info(loginVo.toString());
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        if (ObjectUtil.isEmpty(mobile) || ObjectUtil.isEmpty(password)) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if (!ValidatorUtil.isMobile(mobile)) {
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

        //根据手机号查询用户
        TUser tUser = userMapper.selectById(mobile);
        if (tUser == null) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        log.info(MD5Util.formPassToDBPass(password, tUser.getSalt()));
        if (!MD5Util.formPassToDBPass(password, tUser.getSalt()).equals(tUser.getPassword())) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //生成cookie
        String ticket = UUIDUtil.uuid();

        //将用户信息存入redis中
        redisTemplate.opsForValue().set("tUser:" + ticket, tUser);


        //存入Session，更改方案，存入redis
//        request.getSession().setAttribute(ticket, tUser);

        CookieUtil.setCookie(request, response, "tUserTicket", ticket);
        return RespBean.success(ticket);
    }

    /**
     * @param tUserTicket
     * @return
     */
    @Override
    public TUser getUserByCookie(String tUserTicket, HttpServletRequest request, HttpServletResponse response) {

        if (null == tUserTicket || "".equals(tUserTicket)) {
            return null;
        }
        TUser tUser = (TUser) redisTemplate.opsForValue().get("tUser:" + tUserTicket);

        if (tUser != null) {
            CookieUtil.setCookie(request, response, "tUserTicket", tUserTicket);
        }
        return tUser;
    }

    /**
     * 更新密码
     *
     * @param tUserTicket
     * @param password
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean updatePassword(String tUserTicket, String password, HttpServletRequest request, HttpServletResponse response) {

        TUser user = getUserByCookie(tUserTicket, request, response);
        if (user == null) {
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }

        user.setPassword(MD5Util.inputPassToDbPass(password, user.getSalt()));
        int result = userMapper.updateById(user);
        if (1 == result) {
            redisTemplate.delete("tUser:" + tUserTicket);
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.UPDATE_FAIL);
    }

    /**
     * 获取全部的用户账号和密码
     *
     * @return
     */
    @Override
    public List<TUser> getUserAll() {
        List<TUser> users = userMapper.selectList(new QueryWrapper<>());
        return users;
    }

    /**
     * 注册
     *
     * @param registerVo
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean doRegister(RegisterVo registerVo, HttpServletRequest request, HttpServletResponse response) {
        log.info(registerVo.toString());
        Long mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String username = registerVo.getUsername();
        if (ObjectUtil.isEmpty(mobile) || ObjectUtil.isEmpty(password) || ObjectUtil.isEmpty(username)) {
            return RespBean.error(RespBeanEnum.INFO_NOT_COMPLETE);
        }
        if (!ValidatorUtil.isMobile(mobile.toString())) {
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

        //根据手机号查询用户
        TUser tUser = userMapper.selectById(mobile);
        if (tUser != null) {
            return RespBean.error(RespBeanEnum.USER_EXIST);
        }

        log.info(MD5Util.formPassToDBPass(password, salt));

        TUser user = new TUser();
        user.setPassword(MD5Util.formPassToDBPass(password, salt));
        user.setLoginCount(1);
        user.setId(registerVo.getMobile());
        user.setNickname(registerVo.getUsername());
        user.setLastLoginDate(new Date());
        user.setRegisterDate(new Date());
        user.setSalt(salt);
        int insert = userMapper.insert(user);

        return RespBean.success(null);
    }

}
